package handle

import (
	"note-hub/cache"
	"note-hub/model"
	"note-hub/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
)

func User(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}
	var user model.User
	count_Key := "pass" + username
	cache_count, _ := cache.Rdb.Get(cache.Ctx, count_Key).Int()
	if cache_count >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, count_Key)
		if cache_count == 2 {
			cache.Rdb.Set(cache.Ctx, count_Key, "2", time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误封2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
}
func RoleNode(c *gin.Context) {
	/*
		SELECT * FROM
		nodes LEFT JOIN role_nodes on role_nodes.nid = nodes.id
		WHERE role_nodes.rid =1
	*/
	rid := c.Query("rid")
	node_Key := "id" + rid
	var node model.Node
	cacheData, _ := cache.Rdb.Get(cache.Ctx, node_Key).Result()
	if cacheData == "" {
		model.DB.Table("nodes").
			Joins("LEFT JOIN role_nodes on role_nodes.nid = nodes.id").
			Where("role_nodes.rid =?", rid).Find(&node)
		jsonData, _ := json.Marshal(cacheData)
		cache.Rdb.Set(cache.Ctx, node_Key, string(jsonData), time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &cacheData)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})

}
func CarHou(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size
	var list []model.CarHou
	node_Key := "page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, node_Key).Result()
	/*
			SELECT
		hous.id as Hid,
		cars.static as Static,
		cars.pan as Pan,
		hous.`data` as Data,
		hous.xin as Xin
		FROM hous LEFT JOIN cars on cars.id = hous.car_id
	*/
	if cacheData == "" {
		model.DB.Table("hous").Offset(offset).Limit(size).
			Select(
				"cars.static as Static",
				"cars.pan as Pan",
				"hous.`data` as Data",
				"hous.xin as Xin").
			Joins("LEFT JOIN cars on cars.id = hous.car_id").
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, node_Key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})

}
